/*

This file is part of roomyak.

Copyright (C) 2008 Pixecur Technologies Incorporated (Esotera).
Visit Esotera at http://www.esoteras3.com
 
roomyak is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3, or (at your option)
any later version.
 
roomyak is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.
 
You should have received a copy of the GNU General Public License
along with roomyak; see the file COPYING.  If not, write to 
Pixecur Technologies, 213-31 Peet Street, St. John's, NL, A1B 3W8. 
 
Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
 
*/

package com.datasentinel.os.unix;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.StringTokenizer;
import java.util.logging.Logger;

import com.datasentinel.os.OSToolKit;
import com.datasentinel.os.ProcessIterator;


public abstract class AbstractUNIXToolKit extends OSToolKit
{
	
	private static Logger logger = Logger.getLogger(OSToolKit.class.getName());
	
	public abstract String getOpenFileCommand();
	public String getMACQualifier()
	{
		return "hwaddr";
	}
	
	public String getTempDirDefault()
	{
		String tempFolder = System.getProperty("java.io.tmpdir");
		return tempFolder == null ? "/tmp" : tempFolder;
	}

	public ProcessIterator exec(File dir, String command,String args) throws Exception
	{
		if (args == null || args.length() == 0)
			command = getOpenFileCommand() + " " + toURI(dir, command);
		else
			command += " " + args;
		return new ProcessIterator(Runtime.getRuntime().exec(command, null, dir));
	}
	public void makeLink(File link, File file) throws IOException
	{
		exec(new String[]{"ln", "-s", file.getAbsolutePath(), link.getAbsolutePath()});
	}

	public ArrayList<String> getMacAddresses(ArrayList<String> macs) throws IOException
	{
		String qualifier = getMACQualifier();
		for (Iterator<String> i = exec(new String[]{"ifconfig","-a"}); i.hasNext();)
		{
			String line = i.next().toLowerCase();
			int index = line.lastIndexOf(qualifier);
			if (index >= 0)
			{
				line = line.substring(index + qualifier.length()).trim().replace(':', '-');
				if (new StringTokenizer(line, "-").countTokens() == 6)
					macs.add(line.toUpperCase());
			}				
		}
		return macs;
	}
	
	@Override
	public long getProcessId() throws IOException
	{
		String s = null;
		ProcessIterator pi = exec(new String[]{"bash", "-c", "echo $PPID"});
		if (pi.hasNext())
			s = pi.next().trim();
		pi.close();
		logger.warning("pid ='" + s + "'");
		return s==null?-1:Long.parseLong(s);
	}
	@Override
	public long getProcessId(String processSpecifier) throws IOException
	{
		
		String[] command = new String[]{"/bin/sh", "-c", 
				"ps -a --no-headers -o pid,cmd | egrep '" + processSpecifier + "'"};			

//		logger.info("Obtaining processId: " + command);
		
		Iterator<String> i = exec(command);
		
		if (!i.hasNext())
			return 0;
		String processId =  i.next().trim();
		return Long.parseLong(processId.substring(0, processId.indexOf(' ')));
	}

	@Override
	public boolean killProcess(long processId) throws IOException
	{
		ProcessIterator iterator = exec(new String[] { "kill", "-9",
				String.valueOf(processId) });
		logger.info("Killing process: " + processId);
		try
		{
			return iterator.exitValue() == 0;
		}
		catch (InterruptedException e)
		{
			logger.severe("Unable to kill the process: " + e.getMessage());
			return false;
		}
	}		
}
